package com.tanhua.dubbo.api;

import cn.hutool.core.collection.CollUtil;
import com.tanhua.model.mongo.UserLocation;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.geo.Circle;
import org.springframework.data.geo.Distance;
import org.springframework.data.geo.Metrics;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.geo.GeoJsonPoint;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;

import java.util.List;

@DubboService
public class UserLocationApiImpl implements UserLocationApi {

    @Autowired
    private MongoTemplate mongoTemplate;

    /**
     * 保存或者更新地理位置数据
     * @param userId
     * @param address
     * @param latitude  纬度
     * @param longitude 经度
     */
    public void save(Long userId, String address, Double latitude, Double longitude) {
        //1、判断当前用户的地理位置信息是否存在
        Criteria criteria = Criteria.where("userId").is(userId);
        Query query = Query.query(criteria);
        if(!mongoTemplate.exists(query, UserLocation.class)) {
            //2、如果不存在，保存
            UserLocation ul = new UserLocation();
            ul.setUserId(userId);
            ul.setAddress(address);
            ul.setCreated(System.currentTimeMillis());
            ul.setLocation(new GeoJsonPoint(longitude,latitude));
            mongoTemplate.save(ul);
        }else {
            //3、如果存在，更新  update tabl set localtion=? addres==? where userId=?
            Criteria criteria1 = Criteria.where("userId").is(userId);
            Query query1 = Query.query(criteria);
            Update update = new Update();
            update.set("address",address);
            update.set("location",new GeoJsonPoint(longitude,latitude));
            mongoTemplate.updateFirst(query1,update,UserLocation.class);
        }
    }

    //根据用户id，和距离，搜索附近
    public List<Long> searchNear(Long userId, String miles) {
        //1、根据用户id，查询位置信息获取圆点
        Criteria criteria = Criteria.where("userId").is(userId);
        Query query = Query.query(criteria);
        UserLocation location = mongoTemplate.findOne(query, UserLocation.class);
        //圆点
        GeoJsonPoint point = location.getLocation();
        //2、构造半径
        Long temp = Long.valueOf(miles);
        Distance distance = new Distance(temp/1000, Metrics.KILOMETERS);
        //3、根据圆点和半径绘制圆
        Circle circle = new Circle(point,distance);
        //4、调用MongoTemplate查询
        Criteria criteria1 = Criteria.where("location").withinSphere(circle);
        Query query1 = Query.query(criteria1);
        List<UserLocation> list = mongoTemplate.find(query1, UserLocation.class);
        return CollUtil.getFieldValues(list,"userId",Long.class);
    }
}
